package com.product.magina.wechatserver.service.impl;

import com.product.magina.wechatserver.constant.MessageUtil;
import com.product.magina.wechatserver.model.TextMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;

@Component
@Slf4j
public class CoreService {


    public  String parseWxRequest(HttpServletRequest request)  {
        // xml格式的消息数据
        String respXml = null;
        // 默认返回的文本消息内容
        String respContent = "未知的消息类型！";
        try {
            // 调用parseXml方法解析请求消息
            Map<String, String> requestMap = MessageUtil.parseXml(request);
            // 发送方帐号,一个openID
            String fromUserName = requestMap.get("FromUserName");
            // 开发者微信号
            String toUserName = requestMap.get("ToUserName");
            // 消息类型
            String msgType = requestMap.get("MsgType");
            // 接收用户发送的文本消息内容
            String content = requestMap.get("Content");
            //回复文本消息
            TextMessage textMessage = new TextMessage();
            textMessage.setToUserName(fromUserName);
            textMessage.setFromUserName(toUserName);
            textMessage.setCreateTime(System.currentTimeMillis());
            textMessage.setMsgType(MessageUtil.REQ_MESSAGE_TYPE_TEXT);

            // 文本消息
            if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
//                String url = "\'http://i.ashvsash.com/?s="+URLDecoder.decode(content,"GBK") + "\'";//哎生活被屏蔽了
                String url = "\'http://m.titaixiu.cn/?s="+URLDecoder.decode(content,"GBK") + "\'";// \需要转义
//                String url = "\'http://wb5sai.natappfree.cc/Wechat/testData\'";
                respContent = "搜索结果:"+"<a href="+url+">点击这里</a>";
                textMessage.setContent(respContent);
                String xml = MessageUtil.buildTextMessage(textMessage);
                respXml = xml;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return respXml;
    }
}
